<?php

namespace App\Models;

use App\Util\Url;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\DB;
use App\Util\Tool;
use App\Models\CourseCategory;

//课程表
class Course extends Model
{
    protected $casts = [
        'course_images' => 'json',
    ];

    protected $table = 'c_courses';

    /**
     * @param $pictures
     * @return void
     * 多图片添加使用
     */
    public function setDetailImagesAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['detail_images'] = json_encode($pictures);
        }
    }


    /**
     * @param $pictures
     * @return mixed
     * 多图片读取使用
     */
    public function getDetailImagesAttribute($pictures)
    {
        return json_decode($pictures, true);
    }

    /**获取全部课程后台添加使用
     * @return void
     */
    public function getOptions()
    {
        $options = $this->select('id', 'course_title as text')->get();
        $selectOption = [];
        foreach ($options as $option) {
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }

    public function directory()
    {
        return $this->hasMany('App\Models\Directory', 'courses_id');
    }

    /**
     * 获取课程章节
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function getCoursesSection()
    {
        return $this->hasMany('App\Models\CoursesSection', 'courses_id');
    }

    //工作室
    public function work()
    {
        return $this->belongsTo('App\Models\DoctorWorks', 'work_id');
    }
    //医生
    public function doctor()
    {
        return $this->belongsTo('App\Models\Doctor', 'add_user_id');
    }
    //科室
    public function courses(){
        return $this->belongsTo('App\Models\CourseCategory', 'course_sort_id');
    }
    
    
    public function getChildCateId($param)
    {
        $list =  (new CourseCategory())->where([['pid', '=',$param['category_id']]])->pluck("id")->toArray();
        array_push($list,$param['category_id']);
        return $list;
    }
    
    
    
    /***
     * @param $param
     * 出院须知
     */
    public function leaveHospital($param)
    {
        $work_course = (new WorkRelateCourse());
        $field = "c_work_relate_courses.id";
        $asc = "desc";
        $where = [];
        if (isset($param['score']) && !empty($param['score'])) {  //评价
            if ($param['score'] == 1) {//倒序
                $field = "c_courses.course_score";
                $asc = "desc";
            } else {
                $field = "c_courses.course_score";
                $asc = "asc";
            }
        }
        if (isset($param['sales']) && !empty($param['sales'])) {  //销量
            if ($param['sales'] == 1) {//倒序
                $field = "c_courses.buy_num";
                $asc = "desc";
            } else {
                $field = "c_courses.buy_num";
                $asc = "asc";
            }
        }
        if (isset($param['price']) && !empty($param['price'])) {  //价格
            if ($param['price'] == 1) {//倒序
                $field = "c_courses.course_price";
                $asc = "desc";
            } else {
                $field = "c_courses.course_price";
                $asc = "asc";
            }
        }
        if (isset($param['isbuy']) && !empty($param['isbuy']) && $param['isbuy'] ==1) {  //是否收费
            $where[] = ['c_courses.course_price', '>', 0];
        }
        if (isset($param['work_id']) && !empty($param['work_id'])) {  //医护室
            $where[] = ['c_work_relate_courses.work_id', '=', $param['work_id']];
        }
        if (isset($param['cate_id']) && !empty($param['cate_id'])) {  //工作室自己的id
            $where[] = ['c_work_relate_courses.cate_id', '=', $param['cate_id']];
        }
        if (isset($param['category_id']) && !empty($param['category_id'])) {  //分类id
            //$where[] = ['c_courses.course_sort_id', '=', $param['category_id']];
            $childIds  = $this->getChildCateId($param);
            if (!empty($childIds)) {
                $where[] = [function ($query) use ($childIds) {
                    $query->whereIn('c_courses.course_sort_id', $childIds);
                }];
            }
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $where[] = ['c_courses.course_title', 'like', '%' . $param['title'] . '%'];
        }
        $where[] = ['c_courses.racking', '=', 2]; //上架
        $where[] = ['c_courses.audit_status', '=', 2]; //审核通过
        $where[] = ['c_work_relate_courses.is_online', '=', 1]; //选品库上架
        $res = $work_course->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_courses.work_id')
            ->select("c_courses.*")
            ->addSelect("c_doctor_works.work_name", "c_doctor_works.id as work_id")
            ->addSelect("c_work_relate_courses.id as relate_id")
            ->join('c_courses', 'c_courses.id', '=', 'c_work_relate_courses.course_id')
            ->orderBy($field, $asc)
            ->where($where)
            ->simplePaginate();

        if (!empty($res)) {
            $list = $res->toArray();
            foreach ($list['data'] as $k => $val) {
                if (!empty($val['course_img'])) {
                    $list['data'][$k]['course_img'] = env('APP_URL') . '/upload/' . $val['course_img'];
                }
                if (!empty($val['course_images'])) {
                    $images = json_decode($val['course_images'], true);
                    $img_data = [];
                    if (is_array($images)) {
                        foreach ($images as $kk => $vv) {
                            $img_data[] = env('APP_URL') . '/upload/' . $vv;
                        }
                    } else {
                        $img_data[] = env('APP_URL') . '/upload/' . $val['course_images'];
                    }
                    $list['data'][$k]['course_images'] = $img_data;
                }
            }
            return $list;
        }
        return [];
    }


    /****
     * @param $param
     * @return mixed
     * 课程列表
     */
    public function getList($param)
    {
        $field = "id";
        $asc = "asc";
        $where = [];
        $page = isset($param['page']) && !empty($param['page']) ? $param['page'] : 1;
        if (isset($param['score']) && !empty($param['score'])) {  //评价
            if ($param['score'] == 1) {//倒序
                $field = "course_score";
                $asc = "asc";
            } else {
                $field = "course_score";
                $asc = "desc";
            }
        }
        if (isset($param['sales']) && !empty($param['sales'])) {  //销量
            if ($param['sales'] == 1) {//倒序
                $field = "buy_num";
                $asc = "asc";
            } else {
                $field = "buy_num";
                $asc = "desc";
            }
        }
        if (isset($param['price']) && !empty($param['price'])) {  //价格
            if ($param['price'] == 1) {//倒序
                $field = "course_price";
                $asc = "asc";
            } else {
                $field = "course_price";
                $asc = "desc";
            }
        }
        if (isset($param['isbuy']) && !empty($param['isbuy'])) {  //是否收费
            $where[] = ['lesson_isbuy', '=', $param['isbuy']];
        }
        if (isset($param['work_id']) && !empty($param['work_id'])) {  //医护室
            $where[] = ['work_id', '=', $param['work_id']];
        }
        if (isset($param['category_id']) && !empty($param['category_id'])) {  //分类id
            $where[] = ['course_category_id', '=', $param['category_id']];
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $where[] = ['course_title', 'like', '%' . $param['title'] . '%'];
        }
        $result = $this->where($where)->with(['directory'])->orderBy($field, $asc)->paginate(15, ['*'], 'page', $page);
        if (!empty($result)) {
            $dd = $result->toArray();
            $host = new Url();
            foreach ($dd['data'] as $k => &$v) {
                $v['course_img'] = $host::getHttpHost() . 'upload/' . $v['course_img'];
            }
            return $dd;
        }
        return [];
    }

    /****
     * @param $filter
     * @return mixed
     * 课程详情
     */
    public function getCourseInfo($data)
    {
        $res = $this->where("id", '=', $data['course_id'])->with(['directory'])->first();
        if (!empty($res)) {
            $res->work_name = (new DoctorWorks())->where([['id', '=', $res->work_id]])->value('work_name');
            $res->course_img = Url::getHttpHost() . 'upload/' . $res->course_img;
            if (!empty($res->directory)) {
                foreach ($res->directory as $k => &$v) {
                    $v->courses_video = Url::getHttpHost() . 'upload/' . $v->courses_video;
                }
            }
            $res->is_collect = 0;
            $res->is_user_collect = 0;
            $res->is_buy = 0;
            $res->is_mycourse = 0;
            if (isset($data['user_id'])) {
                $is_col = (new CourseCollect())->where([['course_id', '=', $data['course_id']],
                    ['user_id', '=', $data['user_id']],
                    ['type', '=', 1],
                    ['collect_type', '=', 2]
                ])->first();
                if ($is_col) {
                    $res->is_collect = 1;
                }
//                $buys = (new Order())->where([['user_id', '=', $data['user_id']],['pay_status', '=', 1],['order_status', '<',2]])->first();
                $buys = (new OrderGoods())
                    ->from("c_order_goods as order_goods")
                    ->join("c_orders as order",'order.id','=','order_goods.order_id')
                    ->where([['order_goods.goods_id','=',$data['course_id']],['order.user_id','=',$data['user_id']],['order.pay_status','=',1],['order.order_status','<',2],['order.order_type','=',1]])
                    ->first();
                if ($buys) {
                    $res->is_buy = 1;
                }
                $is_user_col = (new CourseCollect())->where([['course_id', '=', $data['course_id']],
                    ['user_id', '=', $data['user_id']],
                    ['type', '=', 1],
                    ['collect_type', '=', 1]
                ])->first();
                if ($is_user_col) {
                    $res->is_user_collect = 1;
                }
                if (isset($data['work_id'])) {
                    //添加足迹
                    $dd['goods_id'] = $data['course_id'];
                    $dd['user_id'] = $data['user_id'];
                    $dd['work_id'] = $data['work_id'];
                    $dd['type'] = 1;
                    (new Footprint())->addFootPrint($dd);
                    //判断是否添加我的课程
                    $mc = (new MyCourse())->where([['user_id','=',$data['user_id']],['course_id', '=', $data['course_id']],['work_id', '=', $data['work_id']]])->first();
                    if ($mc) {
                        $res->is_mycourse = 1;
                    }
                    //获取工作室的名称
                    $res->work_names  = (new DoctorWorks())->where([['id','=',$data['work_id']]])->value("work_name");
                }
            }
            if ($res->doc_studio_id > 0) {
                $doc_in = (new Doctor())->where([['id', '=', $res->add_user_id]])->first();
                if($doc_in){
                    $res->author = $doc_in->real_name;
                    $res->im_user = 'doctor' . config("omnipay.Im.salt") . $doc_in->id;
                }
            } else {
                $res->author = "平台发布";
                $res->im_user = config("omnipay.PlatformIm");
            }
        }
        return $res->toArray();
    }

    /****
     * @param $filter
     * @return mixed
     * 课程详情没有转数组
     * 编辑课程时候使用
     */
    public function getCourseInfoObj($course_id)
    {
        return $this->where("id", '=', $course_id)->first();
    }


    public function getUserBuyCourseDetail($filter)
    {
        $myCourse = new MyCourse();
        $res = $myCourse->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_my_course.work_id')
            ->join('c_courses', 'c_courses.id', '=', 'c_my_course.course_id')
            ->select("c_courses.*","c_doctor_works.work_name")
            ->where([["c_my_course.user_id",'=',$filter['user_id']],['c_my_course.work_id','=',$filter['work_id']],['c_my_course.course_id','=',$filter['course_id']]])
            ->first();
        $tool = new Tool();
        if (!empty($res)) {
            $val = $res->toArray();
            //消除红点
            (new MyCourse())->where([['work_id','=',$filter['work_id']],['user_id','=',$filter['user_id']],['course_id','=',$filter['course_id']],['is_read','=',1]])->update(['is_read'=>0]);
            $val['is_pay'] = 0;
            $val['is_collect'] = 0;
            $val['is_mycourse'] = 0;
            $val['work_id'] = $filter['work_id'];
            $docs = (new Doctor())->where([['work_id','=',$filter['work_id']]])->first();
            $ds['type'] = 2;
            $ds['user_id'] = $docs->id;
            $ims = Tool::getUserNameForIm($ds);
            $val['im_username'] = $ims['username'];
            //判断课程是否购买
            $this->where([['id', '=', $filter['course_id']]])->increment("visit");
            if (isset($filter['user_id'])) {
                $val['is_pay'] = $this->getIsPay($filter, $filter['user_id']);
                //添加足迹
                $dd['goods_id'] = $res->id;
                $dd['user_id'] = $filter['user_id'];
                $dd['work_id'] = $filter['work_id'];
                $dd['type'] = 1;
                (new Footprint())->addFootPrint($dd);
                //判断是否收藏  work_id
                $is_has = (new CourseCollect())->where([['user_id', '=', $filter['user_id']], ['course_id', '=', $filter['course_id']], ['work_id', '=', $filter['work_id']], ['type', '=', 1]])->first();
                if ($is_has) {
                    $val['is_collect'] = 1;
                }
                //判断是否添加我的课程
                $mc = (new MyCourse())->where([['user_id','=',$filter['user_id']],['course_id', '=', $res->id],['work_id', '=', $filter['work_id']]])->first();
                if ($mc) {
                    $val['is_mycourse'] = 1;
                }
            }
            if (!empty($val['course_img'])) {
                $val['course_img'] = env('APP_URL') . '/upload/' . $val['course_img'];
            }
            if (!empty($val['detail_images'])) {
                $images = json_decode($val['detail_images']);
                $img_data = [];
                if (is_array($images)) {
                    foreach ($images as $kk => $vv) {
                        $img_data[] = env('APP_URL') . '/upload/' . $vv;
                    }
                } else {
                    $img_data[] = env('APP_URL') . '/upload/' . $val['detail_images'];
                }
                $val['detail_images'] = $img_data;
            }
            //获取章节列表
            $directory = (new CoursesSection())->where([['courses_id', '=', $val['id']]])->orderBy("sort_id")->get();
            if ($directory) {
                $chapter = $directory->toArray();
                foreach ($chapter as $key => $values) {
//                    $chapter[$key]['chapter_img'] = $tool->addHostToImage($values['chapter_img']);
                    $chapter[$key]['courses_video'] = $tool->addHostToImage($values['courses_video']);
                }
                $val['courses_section'] = $chapter;
            }
            //精选口碑
            $eval = (new Evaluate())->with(['user'])->where([['types','=',1],['goods_id','=',$filter['course_id']],['score','>',3]])->orderBy("id","desc")->first();
            if(!empty($eval)){
                if ($eval->images) {
                    $eval->images = (new Tool)->addHostToImage($eval->images);
                }
                if ($eval->videos) {
                    $eval->videos = Tool::AddHost($eval->videos);
                }
                $eval->ins_time = Tool::time2Units(strtotime($eval->created_at));
                if (!empty($eval->user->image)) {
                    $eval->user->image = Tool::AddHost($eval->user->image);
                }
                $val['evaluate'] = $eval->toArray();
            }
            return $val;
        }
        return null;
    }




    /****
     * @param $filter
     * @return mixed
     * 客户端课程详情
     */
    public function getCourseDetail($param)
    {
        $work_course = (new WorkRelateCourse());
        $all_id = $work_course::getIdByWorkId($param);
        if (!$all_id) {
            return "该工作室还没有关联该课程";
        }
        $where[] = ['c_work_relate_courses.id', '=', $all_id->id];
        $res = $work_course->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_courses.work_id')
            ->select("c_courses.*")
            ->addSelect("c_doctor_works.work_name")
            ->addSelect("c_work_relate_courses.id as wc_relate_id")
            ->join('c_courses', 'c_courses.id', '=', 'c_work_relate_courses.course_id')
            ->where($where)
            ->first();
        $tool = new Tool();
        if (!empty($res)) {
            $val = $res->toArray();
            $val['is_pay'] = 0;
            $val['is_collect'] = 0;
            $val['is_mycourse'] = 0;
            $val['work_id'] = $param['work_id'];
            $docs = (new Doctor())->where([['work_id','=',$param['work_id']]])->first();
            $ds['type'] = 2;
            $ds['user_id'] = $docs->id;
            $ims = Tool::getUserNameForIm($ds);
            $val['im_username'] = $ims['username'];
            //判断课程是否购买
            $this->where([['id', '=', $param['course_id']]])->increment("visit");
            if (isset($param['user_id'])) {
                $val['is_pay'] = $this->getIsPay($param, $param['user_id']);
                //添加足迹
                $dd['goods_id'] = $res->id;
                $dd['user_id'] = $param['user_id'];
                $dd['work_id'] = $param['work_id'];
                $dd['type'] = 1;
                (new Footprint())->addFootPrint($dd);
                //判断是否收藏  work_id
                $is_has = (new CourseCollect())->where([['user_id', '=', $param['user_id']], ['course_id', '=', $res->id], ['work_id', '=', $param['work_id']], ['type', '=', 1]])->first();
                if ($is_has) {
                    $val['is_collect'] = 1;
                }
                //判断是否添加我的课程
                $mc = (new MyCourse())->where([['user_id','=',$param['user_id']],['course_id', '=', $res->id],['work_id', '=', $param['work_id']]])->first();
                if ($mc) {
                    $val['is_mycourse'] = 1;
                }
                //如果是从患教推送进来的,去除红点
                (new VisitUser())->where([['user_id','=',$param['user_id']],['patient_id','=',$param['course_id']]])->update(['is_read'=>0]);
            }
            if (!empty($val['course_img'])) {
                $val['course_img'] = env('APP_URL') . '/upload/' . $val['course_img'];
            }
            if (!empty($val['detail_images'])) {
                $images = json_decode($val['detail_images']);
                $img_data = [];
                if (is_array($images)) {
                    foreach ($images as $kk => $vv) {
                        $img_data[] = env('APP_URL') . '/upload/' . $vv;
                    }
                } else {
                    $img_data[] = env('APP_URL') . '/upload/' . $val['detail_images'];
                }
                $val['detail_images'] = $img_data;
            }
            //获取章节列表
            $directory = (new CoursesSection())->where([['courses_id', '=', $val['id']]])->orderBy("sort_id")->get();
            if ($directory) {
                $chapter = $directory->toArray();
                foreach ($chapter as $key => $values) {
//                    $chapter[$key]['chapter_img'] = $tool->addHostToImage($values['chapter_img']);
                    $chapter[$key]['courses_video'] = $tool->addHostToImage($values['courses_video']);
                }
                $val['courses_section'] = $chapter;
            }
            //精选口碑
            $eval = (new Evaluate())->with(['user'])->where([['types','=',1],['goods_id','=',$param['course_id']],['score','>',3]])->orderBy("id","desc")->first();
            if(!empty($eval)){
                if ($eval->images) {
                    $eval->images = (new Tool)->addHostToImage($eval->images);
                }
                if ($eval->videos) {
                    $eval->videos = Tool::AddHost($eval->videos);
                }
                $eval->ins_time = Tool::time2Units(strtotime($eval->created_at));
                if (!empty($eval->user->image)) {
                    $eval->user->image = Tool::AddHost($eval->user->image);
                }
                $val['evaluate'] = $eval->toArray();
            }
            return $val;
        }
    }

    /**
     * 判断是否购买
     * */
    public function getIsPay($res, $user_id)
    {
        $val = 0;
        $order = (new OrderGoods())
            ->where([['user_id', '=', $user_id],
                ['work_id', '=', $res['work_id']],
                ['goods_id', '=', $res['course_id']]])
            ->first();
        if (!empty($order)) {
            $order = (new Order())->where([['id', '=', $order->order_id]])->first();
            if (!empty($order)) {
                if ($order->pay_status == 1 && $order->order_status < 1) {
                    $val = 1;
                }
            }
        }
        return $val;
    }

    /**
     * @param $data
     * @return array|string
     * 添加课程
     */
    public function doAddCourses($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['id']) && !empty($data['id'])) {
                $redata = $this->getCourseInfoObj($data['id']);
                $redata->add_user_id = isset($data['add_user_id']) ? $data['add_user_id'] : $redata->add_user_id;
                $redata->course_sort_id = isset($data['course_sort_id']) ? $data['course_sort_id'] : $redata->course_sort_id;
                $redata->is_original = isset($data['is_original']) ? $data['is_original'] : $redata->is_original;
                $redata->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->doc_studio_id;
                $redata->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->work_id;
                $redata->racking = isset($data['racking']) ? $data['racking'] : $redata->racking;
                $redata->source = isset($data['source']) ? $data['source'] : $redata->source;
                $redata->course_title = isset($data['course_title']) ? $data['course_title'] : $redata->course_title;
                $redata->course_img = isset($data['course_img']) ? $data['course_img'] : $redata->course_img;
                $redata->course_info = isset($data['course_info']) ? $data['course_info'] : $redata->course_info;
                $redata->explain = isset($data['explain']) ? $data['explain'] : $redata->explain;
                $redata->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : $redata->lesson_isbuy;
                $redata->course_price = isset($data['course_price']) ? $data['course_price'] : $redata->author_price; //价格
                $redata->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : $redata->commission_rate;
                $res = $redata->save();
                $this->addWorkRelateCourses($data,$data['id']);
            } else {
                //添加
                $this->add_user_id = $data['add_user_id'];
                $this->course_sort_id = $data['course_sort_id'];
                $this->is_original = $data['is_original'];
                $this->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->racking = isset($data['racking']) ? $data['racking'] : 2;
                $this->audit_status = 1;
                $this->source = 1;
                $this->course_title = $data['course_title'];
                $this->course_img = $data['course_img'];
                $this->course_info = $data['course_info'];
                $this->explain = $data['explain'];
                $this->course_price =isset($data['course_price']) ? $data['course_price'] : 0; //后台需要   //期望价格
                $this->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : 0;
                $this->course_price = isset($data['course_price']) ? $data['course_price'] : 0;
                $this->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : 0;
                $res = $this->save();
                $this->addWorkRelateCourses($data,$this->id);
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['course_id' => isset($data['id']) ? $data['id'] : $this->id];
            } else {
                return '添加失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }

    }

    /**
     * @param $data
     * @return array|string
     * ios添加课程
     */
    public function doAddCoursesIos($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['id']) && !empty($data['id'])) {
                $redata = $this->getCourseInfoObj($data['id']);
                $redata->add_user_id = isset($data['add_user_id']) ? $data['add_user_id'] : $redata->add_user_id;
                $redata->course_sort_id = isset($data['course_sort_id']) ? $data['course_sort_id'] : $redata->course_sort_id;
                $redata->is_original = isset($data['is_original']) ? $data['is_original'] : $redata->is_original;
                $redata->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->doc_studio_id;
                $redata->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->work_id;
                $redata->course_title = isset($data['course_title']) ? $data['course_title'] : $redata->course_title;
                $redata->course_img = isset($data['course_img']) ? $data['course_img'] : $redata->course_img;
                $redata->course_info = isset($data['course_info']) ? $data['course_info'] : $redata->course_info;
                $redata->explain = isset($data['explain']) ? $data['explain'] : $redata->explain;
                $redata->free_num = isset($data['free_num']) ? $data['free_num'] : $redata->free_num;
                $redata->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : $redata->lesson_isbuy;
                $redata->course_price = isset($data['course_price']) ? $data['course_price'] : $redata->author_price; //期望价格
                $redata->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : $redata->commission_rate;
                $res = $redata->save();
                $this->addWorkRelateCourses($data,$data['id']);
            } else {
                //添加
                $this->add_user_id = $data['add_user_id'];
                $this->course_sort_id = $data['course_sort_id'];
                $this->is_original = $data['is_original'];
                $this->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->audit_status = 1;
                $this->source = 1;
                $this->course_title = $data['course_title'];
                $this->course_img = $data['course_img'];
                $this->course_info = $data['course_info'];
                $this->explain = isset($data['explain'])?$data['explain']:"";
                $this->free_num =isset($data['free_num']) ? $data['free_num'] : 0;
                $this->course_price =isset($data['course_price']) ? $data['course_price'] : 0; //后台需要   //期望价格
                $this->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : 0;
                $this->course_price = isset($data['course_price']) ? $data['course_price'] : 0;
                $this->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : 0;
                $res = $this->save();
                $this->addWorkRelateCourses($data,$this->id);
                (new CoursesSection())->doAddCoursesSectionIos($data,$this->id);
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['course_id' => isset($data['id']) ? $data['id'] : $this->id];
            } else {
                return '添加失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }

    }

    /**
     * @param $data
     * @return array|string
     * Android添加课程
     */
    public function addCoursesAndroid($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['id']) && !empty($data['id'])) {
                $redata = $this->getCourseInfoObj($data['id']);
                $redata->add_user_id = isset($data['add_user_id']) ? $data['add_user_id'] : $redata->add_user_id;
                $redata->course_sort_id = isset($data['course_sort_id']) ? $data['course_sort_id'] : $redata->course_sort_id;
                $redata->is_original = isset($data['is_original']) ? $data['is_original'] : $redata->is_original;
                $redata->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->doc_studio_id;
                $redata->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : $redata->work_id;
                $redata->course_title = isset($data['course_title']) ? $data['course_title'] : $redata->course_title;
                $redata->course_img = isset($data['course_img']) ? $data['course_img'] : $redata->course_img;
                $redata->course_info = isset($data['course_info']) ? $data['course_info'] : $redata->course_info;
                $redata->explain = isset($data['explain']) ? $data['explain'] : $redata->explain;
                $redata->free_num = isset($data['free_num']) ? $data['free_num'] : $redata->free_num;
                $redata->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : $redata->lesson_isbuy;
                $redata->course_price = isset($data['course_price']) ? $data['course_price'] : $redata->author_price; //期望价格
                $redata->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : $redata->commission_rate;
                $res = $redata->save();
                $this->addWorkRelateCourses($data,$data['id']);
            } else {
                //添加
                $this->add_user_id = $data['add_user_id'];
                $this->course_sort_id = $data['course_sort_id'];
                $this->is_original = $data['is_original'];
                $this->doc_studio_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->work_id = isset($data['doc_studio_id']) ? $data['doc_studio_id'] : 0;
                $this->audit_status = 1;
                $this->source = 1;
                $this->course_title = $data['course_title'];
                $this->course_img = $data['course_img'];
                $this->course_info = $data['course_info'];
                $this->explain = isset($data['explain'])?$data['explain']:"";
                $this->free_num =isset($data['free_num']) ? $data['free_num'] : 0;
                $this->author_price =isset($data['course_price']) ? $data['course_price'] : 0; //后台需要   //期望价格
                $this->lesson_isbuy = isset($data['lesson_isbuy']) ? $data['lesson_isbuy'] : 0;
                $this->course_price = isset($data['course_price']) ? $data['course_price'] : 0;
                $this->commission_rate = isset($data['commission_rate']) ? $data['commission_rate'] : 0;
                $res = $this->save();
                $this->addWorkRelateCourses($data,$this->id);
                (new CoursesSection())->doAddCoursesSectionAndroid($data,$this->id);
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['course_id' => isset($data['id']) ? $data['id'] : $this->id];
            } else {
                return '添加失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }

    }

    /**
     * @param $data
     * 删除课程
     */
    public function del($data)
    {
        $info = $this->getCourseInfoObj($data['course_id']);
        if (empty($info)) {
            return "该课程不存在!";
        }
        if ($info->work_id != $data['work_id']) {  //共享课程
            $res = (new WorkRelateCourse())->where([['course_id', '=', $data['course_id']], ['work_id', '=', $data['work_id']]])->delete();
            if ($res) {
                return true;
            }
            return "删除失败!";
        }
        if ($info->add_user_id != $data['doctor_id']) {
            return "该课程您无权删除!";
        }
        //查询该课程是否有订单
        $order = new Order;
        $orderinfo = $order
            ->join("c_order_goods as goods", "goods.order_id", '=', 'c_orders.id')
            ->select("goods.*")
            ->where([['c_orders.pay_status', '=', 1], ['c_orders.order_type', '=', 1], ['goods.goods_id', '=', $data['course_id']]])->first();
        if ($orderinfo) {
            return "该课程已存在订单,不能删除该课程!";
        }
        //删除课程
        $res = $this::destroy($data['course_id']);
        if ($res) {
            (new WorkRelateCourse())->where([['course_id', '=', $data['course_id']]])->delete();
            (new CourseCollect())->where([['type', '=', 1], ['course_id', '=', $data['course_id']]])->delete();
            return true;
        }
        return "删除失败!";
    }





    /**
     * @param $data
     * @param $art_id
     * @return bool
     * 添加课程关联自己工作室的分类
     * c_work_relate_courses
     */
    public function addWorkRelateCourses($data, $course_id)
    {
        $relate = new  WorkRelateCourse();
        $res = $relate->where([['work_id', '=', $data['doc_studio_id']], ['course_id', '=', $course_id]])->first();
        if ($res) {
            if ($res->cate_id != $data['self_cate_id']) { //分类ID不同,修改分类
                $res->cate_id = $data['self_cate_id'];
                return $res->save();
            }
            return true;
        }
        //添加
        $relate->cate_id = $data['self_cate_id'];
        $relate->work_id = $data['doc_studio_id'];
        $relate->course_id = $course_id;
        return $relate->save();
    }



    /***
     *
     * 视频库
     * 读取分享的课程和自己的课程
     */
    public function getAllCoursesList($param)
    {
        $where[] = ['audit_status', '=', 2];
        $where[] = ['racking', '=', 2];
        $where[] = ['is_share', '=', 1];
        $field = "id";
        $sort = "desc";
        $whereor = [];
        //查看工作室已有视频
        $ids = (new WorkRelateCourse())::getCourseIds($param);
        $selected_ids = (new SelectedGoodsLog())::getSelectedArticleIds($param, 2);
        if (!empty($selected_ids)) {
            $selected_ids = $selected_ids->toArray();
        } else {
            $selected_ids = [];
        }
        //查看自己发布的课程
        if (isset($param['doctor_id'])) {
            $where[] = ['add_user_id', '!=', $param['doctor_id']];
            $w = [];
            if (isset($param['course_sort_id'])) { //分类id
                $w[] = ['course_sort_id', '=', $param['course_sort_id']];
            }
            if (isset($param['title'])) {  //标题搜索
                $w[] = ['course_title', 'like', '%' . $param['title'] . '%'];
            }
//            $self_ids = $this->where([['add_user_id', '=', $param['doctor_id']]])->where($w)->pluck("id");
//            $whereor[] = [function ($query) use ($self_ids) {
//                return $query->whereIn('id', $self_ids);
//            }];
        }
        if (isset($param['course_sort_id'])) { //分类id
            $where[] = ['course_sort_id', '=', $param['course_sort_id']];
        }
        if (isset($param['title'])) {  //标题搜索
            $where[] = ['course_title', 'like', '%' . $param['title'] . '%'];
        }
        if (isset($param['lesson_isbuy'])) {  //标题搜索
            $where[] = ['lesson_isbuy', '=', $param['lesson_isbuy']];
        }
        if (isset($param['hot']) && $param['hot'] == 1) { //热度
            $field = "visit";
            $sort = "desc";
        } elseif (isset($param['hot']) && $param['hot'] == 2) {
            $field = "visit";
            $sort = "asc";
        }
        if (isset($param['price']) && $param['price'] == 1) { //热度
            $field = "course_price";
            $sort = "desc";
        } elseif (isset($param['price']) && $param['price'] == 2) {
            $field = "course_price";
            $sort = "asc";
        }
//        $res = $this->where($where)->whereNotIn('id', $ids)->orWhere($whereor)->orderBy($field, $sort)->simplePaginate();
        $res = $this->where($where)->whereNotIn('id', $ids)->orderBy($field, $sort)->simplePaginate();
        if (!empty($res)) {
            $result = $res->toArray();
            $host = new  Url();
            $work = new DoctorWorks();
            foreach ($result['data'] as $k => &$v) {
                if (in_array($v['id'], $selected_ids)) {
                    $v['selected'] = 1;
                } else {
                    $v['selected'] = 0;
                }
                $v['course_img'] = $host::getHttpHost() . 'upload/' . $v['course_img'];
                if ($v['doc_studio_id'] > 0) {
                    $v['work_names'] = $work->where([['id', '=', $v['doc_studio_id']]])->value("work_name");
                } else {
                    $v['work_names'] = "";
                }
                //视频返利预计可得金额
                $share_work_price = sprintf("%.2f", $v['course_price'] * $v['commission_rate']); //发布工作室得钱
                $platform_money = sprintf("%.2f", $v['course_price'] * $v['platform_rate']); //平台得钱
                $s_money = sprintf("%.2f",($v['course_price'] - $share_work_price - $platform_money));  //本工作室得钱
                $v['self_work_price'] = $s_money > 0 ? $s_money : 0;
            }
            return $result;
        }
        return [];
    }


    /**
     * @param $filter
     * 添加课程关联
     */
    public function addRelateCourses($filter)
    {
        $course_ids = Tool::handelString($filter['course_ids']);
        $course_ids = array_filter($course_ids, function($value) {    //去空
            return $value !== null && $value !== '';
        });
        $filter['g_ids'] = $course_ids;
        $filter['type'] = 2;
        $ret = (new SelectedGoodsLog)->getWorkRightsAndInterests($filter);
        if($ret == false){
            return "您的工作室等级还不够,不能选中更多内容!";
        }
        if (empty($course_ids)) {
            return "课程ID不能为空";
        }
        $relate = new WorkRelateCourse();
        $data = [];
        $log = new SelectedGoodsLog();
        foreach ($course_ids as $k => $v) {
            $relate->where([['course_id', '=', $v], ['work_id', '=', $filter['work_id']]])->delete();
            $log::where([['goods_id', '=', $v], ['work_id', '=', $filter['work_id']], ['type', '=', 2]])->delete();
            $data[$k]['course_id'] = $v;
            $data[$k]['work_id'] = $filter['work_id'];
            $data[$k]['cate_id'] = $filter['cate_id'];
            $data[$k]['created_at'] = date("Y-m-d H:i:s", time());
            $data[$k]['updated_at'] = date("Y-m-d H:i:s", time());
        }
        $yes = DB::table('c_work_relate_courses')->insert($data);
        if ($yes) {
            return true;
        }
        return "添加失败";
    }


    /***
     * 医师端获取我的课程
     */
    public function getMyCourses($param)
    {
        $host = new Url();
        $relate = new WorkRelateCourse();
        $whereor = [];
        $where = [];
        $is_charge = [];
        $field = "id";
        $sort = "desc";
        //科室赛选
        if (isset($param['course_sort_id'])) {
            $where[] = ["course_sort_id", '=', $param['course_sort_id']];
        }
        if (isset($param['is_charge']) && $param['is_charge']==1) {
            $is_charge[] = ["course_price", '=', 0];
        }
        $courses_ids = $relate
            ->join("c_courses as courses", 'courses.id', '=', 'c_work_relate_courses.course_id')
            ->where($where)
            ->where([['c_work_relate_courses.work_id', '=', $param['work_id']]])
            ->pluck("c_work_relate_courses.course_id");
        if (!empty($courses_ids)) {
            $whereor[] = [function ($query) use ($courses_ids) {
                return $query->whereIn('id', $courses_ids);
            }];
        }
        $where[] = ['add_user_id', '=', $param['doctor_id']];
        $res = $this->where($where)->orWhere($whereor)->where($is_charge)->distinct()->orderBy($field, $sort)->simplePaginate()->toArray();
        if (!empty($res['data'])) {
            $doc = (new Doctor())->where([['id', '=', $param['doctor_id']]])->first();
            $work = (new DoctorWorks())->where([['id', '=', $doc->work_id]])->first();
            foreach ($res['data'] as $k => &$v) {
                if ($v['course_img']) {
                    $v['course_img'] = $host::getHttpHost() . 'upload/' . $v['course_img'];
                }
                $v['count_doc'] = $relate->where([['course_id', '=', $v['id']]])->count("id");
                $v['work_room'] = $work->work_name;
                $v['use_nums'] = $relate->where([['course_id', '=', $v['id']]])->count("id");
                if($v['work_id'] == $param['work_id']){ //自己工作室的课程
                    $v['is_my'] = 1;
                    //视频返利预计可得金额
                    //$share_work_price = sprintf("%.2f", $v['course_price'] * $v['commission_rate']); //发布工作室得钱
                    $platform_money = sprintf("%.2f", $v['course_price'] * $v['platform_rate']); //平台得钱
                    $s_money = sprintf("%.2f",($v['course_price'] - $platform_money));  //本工作室得钱
                    $v['self_work_price'] = $s_money > 0 ? $s_money : 0;
                }else{ //售卖方
                    $v['is_my'] = 0;
                    //视频返利预计可得金额
                    $share_work_price = sprintf("%.2f", $v['course_price'] * $v['commission_rate']); //发布工作室得钱
                    $platform_money = sprintf("%.2f", $v['course_price'] * $v['platform_rate']); //平台得钱
                    $s_money = sprintf("%.2f",($v['course_price'] - $share_work_price - $platform_money));  //本工作室得钱
                    $v['self_work_price'] = $s_money > 0 ? $s_money : 0;
                }
            }
        }
        return $res;
    }

    /**
     * @param $param
     * 取消共享和共享
     */
    public function shareCourses($param)
    {
        $info = $this->getCourseInfo($param);
        if ($info['add_user_id'] != $param['doctor_id']) {
            return "您无权分享该视频";
        }
        if ($info['is_share'] == 1) {
            $data = $this->where([['id', '=', $param['course_id']]])->update(['is_share' => 0]);
            if ($data) {
                return 1;
            } else {
                return 2;
            }
        } elseif ($info['is_share'] == 0) {
            $data = $this->where([['id', '=', $param['course_id']]])->update(['is_share' => 1]);
            if ($data) {
                return 3;
            } else {
                return 4;
            }
        }
    }


}